/**
 *  文件上传服务
 *
 */
define(['app','filesaver','fileupload'], function( app ) {
    'use strict';

    app.factory('AgUpload', ['Upload','dataFactoryCRM','$rootScope', 'crmConst','$q','$http', function(Upload, dataFactoryCRM, $rootScope, crmConst, $q, $http) {
        var _AgUpload = {version:0.01,dao:false,url:'att/upload',file:false,status:0,param:{} };

        /**
         * Excel导出下载
         * @param  string view_path   下载Excel文件地址
         * @param  string name     下载文件保存名称
         * @return
         */
        _AgUpload.downExcel = function( view_path, name ){
            var deferred = $q.defer();
            if( !view_path )
                deferred.reject( "下载Excel路径不能为空" );
            else{
                var downloadLink = angular.element('<a></a>');
                downloadLink.attr('href', view_path);
                downloadLink.attr('download',  name );
                downloadLink[0].click();
                deferred.resolve({status:200});

                /*$http({
                    url: view_path,
                    method: 'get',
                    responseType: 'arraybuffer'
                }).success(function (data, status, headers) {
                    var type = '';
                    var n = view_path.lastIndexOf('.');
                    type = view_path.substring( n+1);
                    switch ( type ) {
                        case 'xlsx':
                            type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                            break;
                        case 'xls':
                            type = 'application/vnd.ms-excel';
                            break;
                        default:
                            type = '';
                            break;
                    }
                    if( !type )
                        deferred.reject("Excel文件类型不支持");
                    else{
                        saveAs(new Blob([data], { type: type }), name||decodeURI(headers()["x-filename"])||view_path.substring( view_path.lastIndexOf('/')+1)  );
                        deferred.resolve({header:headers,status:status});
                    }
                }).error(function (data, status) {
                    deferred.reject("下载文件失败");
                });*/
            }

            return deferred.promise;
        }

        //添加文件
        _AgUpload.add = function( vfile ){
            this.file = vfile ;
            this.status = 0;
        };


        //删除文件
        _AgUpload.del = function ( vfile ){
            if( !this.file )
                return true;

        };

        _AgUpload.param_add = function( _key, _v){
            this.param[_key] = _v ;
        };

        _AgUpload.param_del = function( _key ){
            if( this.param[_key] != undefined  )
                delete this.param[_key];
        };

        _AgUpload.setUrl = function( _url ){
            if( !_url )
                return false;
            return this.url = _url;
        };

        //返回正在上传的状态
        _AgUpload.status = function(){
            return this.status;
        };

        //开始上传文件
        _AgUpload.start = function(){
            var deferred = $q.defer();
            this.param.file = this.file;
            this.param.name = 'file';
            Upload.upload({
                url: crmConst.BASE + crmConst.API + _AgUpload.url,
                data: this.param
            }).then(function ( _data ) {
                _AgUpload.status = 1;
                if( _data && _data.status == 200 ){
                    deferred.resolve( _data.data );
                }
                else
                    deferred.reject( "上传失败" );
            }, function (resp) {
                _AgUpload.status = -1;
                deferred.reject( "上传失败" );
            }, function (evt) {
                var percent = parseInt( evt.loaded / evt.total );
                _AgUpload.status = percent;
            });

            return deferred.promise;
        };

        //结束文件上传
        _AgUpload.stop = function(){
            //
        };

        return _AgUpload;
    }
    ]);
});